# This PowerShell script was released under the Ms-PL license
# http://www.opensource.org/licenses/ms-pl.html
# This script was originally intended for use with Microsoft Dynamics AX 2009
# and maintained and distributed as a project on CodePlex
# http://dynamicsaxbuild.codeplex.com

param(
	[string] $aosService = $(throw "AOS service name Required"),
	[string] $applicationPath = $(throw "AOS application path required"),
	[string] $SOURCEPATH = $(throw "Path to the source directory required"),
	[string] $buildLayer = $(throw "Name of layer being built is required"),
	[string] $LAYERSTOCLEAN = "",
	[string] $logPath = ""
	)

# Remove object and label indexes
if((Test-Path ($applicationPath + "axapd.aoi"))) { Remove-Item -Force ($applicationPath + "axapd.aoi") }
if((Test-Path ($applicationPath + "`\old`\axapd.aoi"))) { Remove-Item -Force ($applicationPath + "`\old`\axapd.aoi") }
if((Test-Path ($applicationPath + "*.ali"))) { Remove-Item -Force ($applicationPath + "*.ali") }

# Function to clear out layer artifacts
Function CleanLayer([string] $layer)
{
	if((Test-Path ($applicationPath + "ax" + $layer + ".aod"))) {	Move-Item -Force ($applicationPath + "ax" + $layer + ".aod") ($applicationPath + "old`\") }
	if((Test-Path ($applicationPath + "ax" + $layer + ".add"))) { Remove-Item -Force ($applicationPath + "ax" + $layer + ".add") }
	if((Test-Path ($applicationPath + "ax" + $layer + ".ahd"))) { Remove-Item -Force ($applicationPath + "ax" + $layer + ".ahd") }
	if((Test-Path ($applicationPath + "ax" + $layer + ".khd"))) { Remove-Item -Force ($applicationPath + "ax" + $layer + ".khd") }
}

# Clean the layer we're building
CleanLayer $buildLayer

# Clean layers specified in the extra list
$layersToCleanList = $LAYERSTOCLEAN.Split(",")
if ($layersToCleanList -ne $null)
{
	foreach($layerToClean in $layersToCleanList)
	{
		CleanLayer $layerToClean
	}
}

# Check if we have labels
if((Test-Path ($SOURCEPATH + "`\labels")))
{
# Remove label indexes
	Remove-Item -Force ($applicationPath + "*.ali")
# Copy label files that actually contain something
}

# Remove any log files (this is the import log)
if((Test-Path ($logPath + "*.log")))
{
	Remove-Item -Force ($logPath + "*.log")
}
